#!/usr/bin/python
# -*- coding: utf-8 -*-

import sys
import os
from datetime import datetime


# local host name where host database
WP_DATABASE_HOST = '***'
# local username
WP_DATABASE_USERNAME = '***'
# local userpassword
WP_DATABASE_PASSWORD = '***'
# local database name
WP_DATABASE = '***'
# target host url
WP_URL = '***'


def run(cmd):
	return os.system(cmd)


def get_time():
	time_format = '%Y%m%d%H%M%S'
	return datetime.today().strftime(time_format)


def wp_backup():
	global WP_DATABASE_HOST, WP_DATABASE_NAME, WP_DATABASE_PASSWORD, WP_DATABASE_USERNAME

	# create dir of backup file
	backup_dir = 'wp-backup-%s' % get_time()
	os.mkdir(backup_dir)

	project_path = os.getcwd()

	# install zip cmd
	run('yum install zip')

	# create zip command
	wp_zip_path = os.path.join(project_path, backup_dir, 'wp-backup.zip')
	cmd_zip = 'zip -r %s .' % wp_zip_path
	print cmd_zip

	# create backup sql command
	wp_sql_path = os.path.join(backup_dir, 'wp-backup.sql')
	cmd_backup_mysql = 'mysqldump -u%s -p%s %s > %s' % (WP_DATABASE_USERNAME, WP_DATABASE_PASSWORD, WP_DATABASE, wp_sql_path)
	print cmd_backup_mysql

	# create copy self command
	script_path = os.path.join(sys.path[0], 'wp.py')
	wp_script_path = os.path.join(backup_dir, 'wp.py')
	cmd_copy_self = 'cp %s %s' % (script_path, wp_script_path)

	# write wp-import mysql
	wp_sql_url = 'update wp_options set option_value=\\\'%s\\\' where option_id=1 or option_id=2\;' % WP_URL
	wp_import_sql_path = os.path.join(backup_dir, 'wp-import.sql')
	wp_create_database = 'CREATE DATABASE wordpress DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci\;'
	run('touch %s' % wp_import_sql_path)
	run('echo %s >> %s' % ('drop database if exists wordpress\;', wp_import_sql_path))
	run('echo %s >> %s' % (wp_create_database, wp_import_sql_path))
	run('echo %s >> %s' % ('use wordpress\;', wp_import_sql_path))
	run('echo %s >> %s' % ('source wp-backup.sql\;', wp_import_sql_path))
	run('echo %s >> %s' % (wp_sql_url, wp_import_sql_path))

	# backup /var/www/html
	os.chdir('/var/www/html/')
	run(cmd_zip)
	os.chdir(project_path)

	run(cmd_backup_mysql)
	run(cmd_copy_self)

	# zip all
	cmd_zip_all = 'zip -r %s.zip %s' % (backup_dir, backup_dir)
	run(cmd_zip_all)

	# delete all things
	cmd_delete_all = '\\rm -r %s' % backup_dir
	run(cmd_delete_all)


def wp_restore():
	wp_dir = '/var/www/html/'

	# install unzip
	run('yum install unzip')

	# create unzip command
	cmd_unzip = 'unzip wp-backup.zip -d %s' % wp_dir
	run(cmd_unzip)

	# get right
	cmd_right = 'chmod -R 777 %s' % wp_dir
	run(cmd_right)

	# import sql
	cmd_import_sql = 'mysql -u%s -p%s -f < %s' % (WP_DATABASE_USERNAME, WP_DATABASE_PASSWORD, 'wp-import.sql')
	run(cmd_import_sql)


if __name__ == '__main__':
	# option tips
	print '1. backup wordpress'
	print '2. restore wordpress'
	opt = input('Please type the task to be excute: ')

	if opt == 1:
		wp_backup()
	elif opt == 2:
		wp_restore()
	else:
		print 'cannot not recognize the option you type.'